using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;
using System.IO;
using System.Xml.Serialization;

namespace DatabaseManager.StoredConnections
{
    /// <summary>
    /// Describes one file which holds a list of stored connection entries
    /// </summary>
    public class StoredConnectionFile
    {
        private SymmetricAlgorithm _symmetricAlgorithm;
        private string _fileName;
        private string _key;
        private string _iv;
        private List<StoredConnection> _storedConnections;
        private bool _isEditable;

        /// <summary>
        /// Initializes a new instance of the <see cref="StoredConnectionFile"/> class.
        /// </summary>
        /// <param name="fileName">Name of the encrypted file.</param>
        /// <param name="symmetricAlgorithm">The symmetric algorithm, which is used for encryption.</param>
        /// <param name="key">The encryption key.</param>
        /// <param name="iv">The initialization vector for the encryption.</param>
        /// <param name="editable">if set to <c>false</c> a lock icon is displayed in the connection manager dialog.</param>
        public StoredConnectionFile(
            string fileName, 
            SymmetricAlgorithm symmetricAlgorithm,
            string key,
            string iv,
            bool editable)
        {
            _fileName = fileName;
            _symmetricAlgorithm = symmetricAlgorithm;
            _key = key;
            _iv = iv;
            _isEditable = editable;

            _storedConnections = new List<StoredConnection>();
        }

        /// <summary>
        /// Gets or sets the name of the file.
        /// </summary>
        /// <value>The name of the file.</value>
        public string FileName
        {
            get { return _fileName; }
            set { _fileName = value; }
        }

        /// <summary>
        /// Gets or sets the encryption key.
        /// </summary>
        /// <value>The key.</value>
        public string Key
        {
            get { return _key; }
            set { _key = value; }
        }

        /// <summary>
        /// Gets or sets the initialization vector for the encryption.
        /// </summary>
        /// <value>The initialization vector for the encryption.</value>
        public string IV
        {
            get { return _iv; }
            set { _iv = value; }
        }

        /// <summary>
        /// Gets or sets the symmetric algorithm, which is used for encryption.
        /// </summary>
        /// <value>The symmetric algorithm, which is used for encryption.</value>
        public SymmetricAlgorithm UsedSymmetricAlgorithm
        {
            get { return _symmetricAlgorithm; }
            set { _symmetricAlgorithm = value; }
        }

        /// <summary>
        /// Gets the list of stored connection entries.
        /// </summary>
        /// <value>The list of stored connection entries.</value>
        public List<StoredConnection> StoredConnections
        {
            get { return _storedConnections; }
        }

        /// <summary>
        /// Gets a value indicating whether stored connection entries in of this instance are editable.
        /// </summary>
        /// <value>
        /// 	<c>true</c> then stored connection entries in this file will be editable in the connection manager dialog; otherwise, <c>false</c>.
        /// </value>
        public bool IsEditable
        {
            get { return _isEditable; }
        }

        /// <summary>
        /// Deserialize and decrypt the xml file and load all values in the list of stored connection entries.
        /// </summary>
        public void Load()
        { 
            _storedConnections = new List<StoredConnection>();

            if (File.Exists(_fileName))
            {
                StreamReader streamReader = new StreamReader(_fileName);
                XmlSerializer xmlSerializer = new XmlSerializer(typeof(List<StoredConnection>));

                //Decryption
                ASCIIEncoding asciiEnc = new ASCIIEncoding();

                CryptoStream cryptoStream = new CryptoStream(
                        streamReader.BaseStream,
                        _symmetricAlgorithm.CreateDecryptor(
                            asciiEnc.GetBytes(_key),
                            asciiEnc.GetBytes(_iv)),
                        CryptoStreamMode.Read);

                _storedConnections = (List<StoredConnection>)xmlSerializer.Deserialize(cryptoStream);

                streamReader.Close();
            }
        }

        /// <summary>
        /// Encrypt and serialize the list of stored connection entries into the the xml file.
        /// </summary>
        public void Save()
        {
            StreamWriter streamWriter = new StreamWriter(_fileName);
            XmlSerializer xmlSerializer = new XmlSerializer(typeof(List<StoredConnection>));

            //Encryption
            ASCIIEncoding asciiEnc = new ASCIIEncoding();

            CryptoStream cryptoStream =
                new CryptoStream(
                    streamWriter.BaseStream,
                    _symmetricAlgorithm.CreateEncryptor(
                        asciiEnc.GetBytes(_key),
                        asciiEnc.GetBytes(_iv)),
                        CryptoStreamMode.Write);

            xmlSerializer.Serialize(cryptoStream, _storedConnections);
            cryptoStream.FlushFinalBlock();
            streamWriter.Close();
        }
    }
}
